﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using Newtonsoft.Json.Linq;

namespace NetCoreCMS.Web.Areas.Admin.Controllers
{
    public class User_ListController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Users/user_list.cshtml";
        protected int totalCount;
        protected int page;
        protected int pageSize;

        protected int group_id;
        protected string start_time = string.Empty;
        protected string end_time = string.Empty;
        protected string keywords = string.Empty;
        public IUsersService _users { get; set; }
        public IUser_groupsService _user_groups { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            ChkAdminLevel("user_list", CMSEnums.ActionEnum.View.ToString()); //检查权限
            int.TryParse(Request.Query["group_id"],out this.group_id);
            this.keywords = Request.Query["keywords"];
            this.start_time = Request.Query["start_time"];
            this.end_time = Request.Query["end_time"];

            int.TryParse(Request.Query["pagesize"], out this.pageSize);
            if (this.pageSize > 0)
            {
                Response.Cookies.Append("user_list_page_size", this.pageSize.ToString());
            }
            else
            {
                this.pageSize = GetPageSize(10); //每页数量
            }
            // 绑定页面数据
            ViewBag.PageSize = this.pageSize;
            ViewBag.Keywords = this.keywords;
            ViewBag.GroupId = this.group_id;
            ViewBag.StartTime = this.start_time;
            ViewBag.EndTime = this.end_time;
        }

        //
        // GET: /admin/User_List/

        public ActionResult Index()
        {
            TreeBind("where is_lock=0 order by grade asc,id asc"); //绑定类别
            RptBind("where id>0" + CombSqlTxt(this.group_id, this.start_time, this.end_time, this.keywords), "reg_time desc,id desc");
            return View(WEB_VIEW);
        }

        #region 绑定组别=================================
        private void TreeBind(string strWhere)
        {
            var dt = _user_groups.GetList(strWhere);
            List<SelectListItem> groupListItems = new List<SelectListItem>();
            groupListItems.Add(new SelectListItem() { Text = "请选择组别...", Value = "" });
            foreach (User_groups dr in dt)
            {
                groupListItems.Add(new SelectListItem() { Text = dr.title, Value = dr.id.ToString() });
            }
            ViewData["groupListItems"] = groupListItems;
        }
        #endregion

        #region 数据绑定=================================
        private void RptBind(string _strWhere, string _orderby)
        {
            int.TryParse(Request.Query["page"], out this.page);
            this.page = this.page <= 0 ? 1 : this.page;
            ViewData["list"] = _users.GetList(this.page, this.pageSize, _strWhere, _orderby, null);
            this.totalCount = _users.RecordCount(_strWhere);
            string pageUrl = Utils.CombUrlTxt("index", "group_id={0}&start_time={1}&end_time={2}&keywords={3}&page={4}",
                this.group_id.ToString(), this.start_time, this.end_time, this.keywords, "__id__");
            ViewBag.PageContent = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(int _group_id, string _start_time, string _end_time, string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (_group_id > 0)
            {
                strTemp.Append(" and group_id=" + _group_id);
            }
            DateTime dtemp;
            if (!string.IsNullOrEmpty(_start_time))
            {
                
                if(DateTime.TryParse(_start_time, out dtemp))
                strTemp.Append(" and datediff(d,reg_time,'" + _start_time + "')<=0");
            }            
            if (!string.IsNullOrEmpty(_end_time))
            {
                if (DateTime.TryParse(_end_time, out dtemp))
                    strTemp.Append(" and datediff(d,reg_time,'" + _end_time + "')>=0");
            }            
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (user_name like '%" + _keywords + "%' or mobile like '%" + _keywords + "%' or email like '%" + _keywords + "%' or nick_name like '%" + _keywords + "%')");
            }
            return strTemp.ToString();
        }
        #endregion

        #region 返回用户每页数量=========================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Request.Cookies["user_list_page_size"], out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        //批量删除
        [HttpPost]
        public ActionResult SubmitDelete()
        {
            ChkAdminLevel("user_list", CMSEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken record = jobject["list"];
            int id;
            foreach (JToken item in record)
            {
                if (int.TryParse(item["id"].ToString(), out id))
                {
                    if (_users.Delete(id))
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            AddAdminLog(CMSEnums.ActionEnum.Delete.ToString(), "删除用户" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string script = JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index",
                            "group_id={0}&start_time={1}&end_time={2}&keywords={3}",
                            this.group_id.ToString(), this.start_time, this.end_time, this.keywords));
            return Content(script);
        }
    }
}
